package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {
    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/list",name = "展示购销合同下货物列表数据")
    public String list(String contractId,@RequestParam(name = "page",defaultValue = "1") Integer pageNum , //这个name="page" 不能修改的
                       @RequestParam(name = "pageSize",defaultValue = "5") Integer pageSize){
//        跳转到新增货物并且显示货物列表的页面
//        需要向request域中放两个数据：1、用来生成货物的工厂  2、这个合同下的所有货物数据
//         查询用来生成货物的工厂数据 select * from co_factory where ctype='货物'
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
//        查询此合同下的所有货物数据  select * from 货物表 where 合同id=？
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(example, pageNum, pageSize);
        request.setAttribute("page",pageInfo);

        //        为了保存货物时关联合同
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-list";
    }
    @RequestMapping(value="/edit",name="保存合同下货物的方法")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        //完成七牛云上传 返回url 保存到货物图片属性上
        String upload=null;
        try {
            if (productPhoto!=null){
                upload=fileUploadUtil.upload(productPhoto);
            }
        }catch (Exception e){
            upload=null;
            System.out.println(e.getMessage());
        }
        contractProduct.setProductImage(upload);

        if(StringUtils.isEmpty(contractProduct.getId())) {
            //		1.设置货物id
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date());
            contractProductService.save(contractProduct);
        }else{
            contractProductService.update(contractProduct);
        }
        //页面跳转
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }
    @RequestMapping(value="/toUpdate",name="进入修改合同下的货物页面")
    public String toUpdate(String id) {
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        //查询所有的厂家列表
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria1 = factoryExample.createCriteria();
        criteria1.andCtypeEqualTo("货物");
        List factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
        return "/cargo/product/product-update";
    }
    @RequestMapping(value="/delete",name="删除货物方法")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }
    @RequestMapping(value="/toImport",name="跳转刀上传货物页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }
    @RequestMapping(value="/import",name="上传购销合同货物方法")
    public String importXls(String contractId,MultipartFile file) throws Exception {
        //创建一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowIndex = sheet.getLastRowNum();
        ArrayList<ContractProduct> list = new ArrayList<>();
        for (int i = 1; i <=lastRowIndex; i++) {
            //row 获取行 sheet.getRow(i)
            XSSFRow row = sheet.getRow(i);
            ContractProduct product = new ContractProduct();
            String factoryName = row.getCell(1).getStringCellValue(); //生产厂家
            product.setFactoryName(factoryName);
            String productNo = row.getCell(2).getStringCellValue();  //货号
            product.setProductNo(productNo);
            Integer cnumber = ((Double) row.getCell(3).getNumericCellValue()).intValue();//数量
            product.setCnumber(cnumber);
            String packingUnit = row.getCell(4).getStringCellValue();//包装单位
            product.setPackingUnit(packingUnit);
            String loadingRate = row.getCell(5).getNumericCellValue() + "";
            product.setLoadingRate(loadingRate);
            Integer boxNum = ((Double)row.getCell(6).getNumericCellValue()).intValue();
            product.setBoxNum(boxNum);
            Double price = row.getCell(7).getNumericCellValue();
            product.setPrice(price);
            String productDesc = row.getCell(8).getStringCellValue();
            product.setProductDesc(productDesc);
            String productRequest = row.getCell(9).getStringCellValue();
            product.setProductRequest(productRequest);
            product.setContractId(contractId);
            product.setCompanyName(getCompanyName());
            product.setCompanyId(getCompanyId());
            product.setId(UUID.randomUUID().toString());
            product.setCreateDept(getUser().getDeptId());
            product.setCreateBy(getUser().getId());
            product.setCreateTime(new Date());
            list.add(product);

        }
        contractProductService.saveList(list);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }
}
